package mavenFy.fyDownLoader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

final class DownLoadTask implements Runnable {

    private static OkHttpClient client = new OkHttpClient();
    
    protected static Queue<TaskBean> queueTask = new ConcurrentLinkedQueue<TaskBean>();
    
    
    private boolean downFile(String url,File file){
        try{
            if(url==null || file==null) {
                throw new RuntimeException("url或file没有赋值");
            }
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException ex) {
                    Logger.getLogger(DownLoadTask.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                InputStream fis = response.body().byteStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] data = null;
                try {
                    data = readInputStream(fis);
                    fos.write(data);
                    fos.flush();
                    fos.close();

                    response.close();
                } catch (Exception ex) {
                    Logger.getLogger(DownLoadTask.class.getName()).log(Level.SEVERE, null, ex);
                }

                return true;
            } else {
                System.out.println(url+"获取失败");
                return false;
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DownLoadTask.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(DownLoadTask.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }finally {
        }
    }
    private static byte[] readInputStream(InputStream inStream) throws Exception {
        // TODO Auto-generated method stub
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1 ){ 
            outStream.write(buffer, 0, len);  
        }
        inStream.close(); 
        return outStream.toByteArray(); 
    }
    
    public void run() {
        //是否休息过
        boolean rest = false;
        while(true) {
            for(TaskBean task = queueTask.poll();task!=null;task = queueTask.poll()) {
                System.out.println("还剩"+queueTask.size()+"个任务");
                rest=false;
                downFile(task.getUrl(),task.getFile());
            }
            //如果没有休息，就休息一分钟，如果休息过了，就完成任务；
            if(!rest) {
                try {
                    TimeUnit.MINUTES.sleep(1);
                    rest=true;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else {
                break;
            }
        }
    }
}
